package com.dajia.hefei.nbiot.util;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.*;

public class CacheUtil {
    private static Map<String, Entity> cacheMap = new HashMap<>();

    public static <T> T get(String key, Class<T> cls) {
        Object obj = get(key);
        if (null != obj) {
            return (T) obj;
        }
        return null;
    }

    public static Object get(String key) {
        if (cacheMap.containsKey(key)) {
            Entity entity = cacheMap.get(key);
            if (null != entity && System.currentTimeMillis() < entity.getExpiresAt()) {
                return entity.getObj();
            }
        }
        return null;
    }

    public static void set(String key, Object value, int expires/* 单位秒 */) {
        if (null != key && null != value) {
            cacheMap.put(key, new Entity(System.currentTimeMillis() + expires * 1000, value));
        }
    }

    @Data
    @AllArgsConstructor
    private static class Entity {
        private long expiresAt;
        private Object obj;
    }

    public static void main(String[] args) {
        List<String> list = new ArrayList<>(Arrays.asList("abcdefg".split("")));
        CacheUtil.set("key", list, 10);
        System.out.println(CacheUtil.get("key", List.class).size());
        try {
            Thread.sleep(11000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(CacheUtil.get("key", String.class));
    }
}
